# app/user_mgmt.py
from datetime import datetime, date

from flask import Blueprint, request, jsonify, session, abort
from functools import wraps
from . import db
from .models import User

user_mgmt_bp = Blueprint('user_mgmt', __name__, url_prefix='/api/users')


def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        uid = session.get('user_id')
        if not uid:
            abort(401, description="未登录")
        user = User.query.get(uid)
        if not user or not user.is_admin:
            abort(403, description="无权限")
        return f(*args, **kwargs)
    return decorated_function


# 所有本蓝图路由都需管理员权限
@user_mgmt_bp.before_request
@admin_required
def ensure_admin():
    pass


@user_mgmt_bp.route('', methods=['GET'])
def list_users():
    users = User.query.order_by(User.id).all()
    return jsonify([{
        "id": u.id,
        "username": u.username,
        "full_name": u.full_name,
        "expiry_date": u.expiry_date.isoformat() if u.expiry_date else None,
        "is_active": u.is_active,
        "is_admin": u.is_admin,
        "remarks": u.remarks
    } for u in users]), 200


@user_mgmt_bp.route('', methods=['POST'])
def create_user():
    data = request.get_json() or {}
    username   = data.get('username')
    password   = data.get('password')
    full_name  = data.get('full_name')
    expiry_str = data.get('expiry_date')
    is_admin   = bool(data.get('is_admin', False))
    remarks    = data.get('remarks')

    if not username or not password:
        return jsonify({"error": "用户名和密码必填"}), 400
    if User.query.filter_by(username=username).first():
        return jsonify({"error": "用户名已存在"}), 400

    user = User(
        username=username,
        full_name=full_name,
        is_admin=is_admin,
        remarks=remarks
    )
    user.set_password(password)
    # 处理 expiry_date / is_active
    if expiry_str:
        try:
            exp = datetime.strptime(expiry_str, '%Y-%m-%d').date()
        except ValueError:
            return jsonify({"error": "有效期格式错误"}), 400
        user.expiry_date = exp
        user.is_active   = (exp >= date.today())
    else:
        user.is_active = True

    db.session.add(user)
    db.session.commit()
    return jsonify({"message": "创建成功", "id": user.id}), 201


@user_mgmt_bp.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    """
    编辑用户信息（不修改密码）：
    JSON 可包含 username, is_admin, is_active
    """
    user = User.query.get_or_404(user_id)
    data = request.get_json() or {}

    new_name = data.get('username')
    if new_name and new_name != user.username:
        if User.query.filter_by(username=new_name).first():
            return jsonify({"error": "用户名已存在"}), 400
        user.username = new_name

    if 'is_admin' in data:
        user.is_admin = bool(data['is_admin'])
    if hasattr(user, 'is_active') and 'is_active' in data:
        user.is_active = bool(data['is_active'])

    db.session.commit()
    return jsonify({"message": "更新成功"}), 200


@user_mgmt_bp.route('/<int:user_id>/reset_password', methods=['POST'])
def reset_password(user_id):
    """
    重置用户密码：
    POST /api/users/<user_id>/reset_password
    JSON body: { "new_password": "newpass123" }
    """
    user = User.query.get_or_404(user_id)
    data = request.get_json() or {}
    new_pwd = data.get('new_password')
    if not new_pwd:
        return jsonify({"error": "新密码必填"}), 400

    user.set_password(new_pwd)
    db.session.commit()
    return jsonify({"message": "密码已重置"}), 200


@user_mgmt_bp.route('/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    """
    删除用户（物理删除），URL: DELETE /api/users/<user_id>
    """
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({"message": "删除成功"}), 200
